﻿using System;
using System.Web.Security;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Linq;
using System.Web;
using CMS.Web.Engine;

namespace CMS.Web.Data
{
    public interface IUsersRepository
    {
        IUserEntity Login(string login, string password);
        void Logoff(); 
    }
    public class UsersRepository : IUsersRepository
    {
        private IEnumerable<IUserEntity> _users;
        public UsersRepository()
        {
            _users = XElement.Load(HttpContext.Current.Server.MapPath("~/Users.xml")).Elements("user").Select(x => (IUserEntity)new UserEntity
            {
                ID = x.AttributeValue<int>("ID"),
                Login = x.AttributeValue<string>("login"),
                Password = x.AttributeValue<string>("password"),
                DisplayName = x.AttributeValue<string>("displayName")
            });
        }
        public IUserEntity Login(string login, string password)
        {
            IUserEntity user = _users.SingleOrDefault(x => x.Login.Equals(login, StringComparison.InvariantCultureIgnoreCase)
                && x.Password.Equals(password));

            if (user.IsNull())
                throw new Exception("Ошибка безопасности.");

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                  1,                                    // ticket version
                  user.Login,                           // authenticated username
                  DateTime.Now,                         // issueDate
                  DateTime.Now.AddMinutes(30),          // expiryDate
                  false,                                // true to persist across browser sessions
                  "Administrators|Content Managers",    // can be used to store additional user data
                  FormsAuthentication.FormsCookiePath); // the path for the cookie

            string encryptedTicket = FormsAuthentication.Encrypt(ticket);
            HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket));

            return user;
        }

        public void Logoff()
        {
            FormsAuthentication.SignOut();
        }
    }

    public class UserEntity : IUserEntity
    {
        public int ID { get; set; }
        public string Login { get; set; }
        public string Password { get; set; }
        public string DisplayName { get; set; }
    }
}